import React, { useState,useEffect,useMemo } from 'react';
import { Text, View,Button,usePageEvent,navigateTo,Image,hideMenuButton,getStorage,setStorage,showToast,onDpDataChange} from '@ray-js/ray';
import styles from './index.module.less';
import space_ball from '../../assets/images/tab/space_ball.png'
import space_ball1 from '../../assets/images/tab/space_ball1.png'
import space_ball2 from '../../assets/images/tab/space_ball2.png'
import space_ball3 from '../../assets/images/tab/space_ball3.png'
import space_ball4 from '../../assets/images/tab/space_ball4.png'
import match from '../../assets/images/tab/match.png'
import start from '../../assets/images/tab/start_match.png'
import friend from '../../assets/images/tab/friend.png'
import { useActions, useProps,utils } from '@ray-js/panel-sdk';
import FriendBall from '../../components/FriendBall';
import InformationPopup from '../../components/information_popup';
import{sp_switch_code,sp_contact_info_code,sp_contact_msg_code} from '@/constant/dpCodes';
import {ClosePosition,FarPosition} from './RandomPosition.jsx'
import throttle from 'lodash/throttle';

//导出模块
export default function space() {
  const actions = useActions();
  const [remaining,setremaining]=useState(5);
  const [isOn,setisOn]=useState(false);

  //附近球球信息获取并添加进列表
  const [isFirstLoad1,setisFirstLoad1]=useState(false);
  const [deviceList, setDeviceList] = useState([]);
  const sp_contact_info = useProps(props => props[sp_contact_info_code]);
  const { parseJSON } = utils;
  useEffect(() => {
    //首次加载页面不执行
    if(!isFirstLoad1)
    {
      setisFirstLoad1(true);
      return;
    }
    const dev_infomation=parseJSON(sp_contact_info);

    //根据下发的距离的不同设置
    let TempDistance;
    let isDim;
    if(dev_infomation.distance==="0,20")
    {
      TempDistance=20;
      isDim=false;
    }
    else if(dev_infomation.distance==="20,100")
    {
      TempDistance=100;
      isDim=true;
    }
    else{
      TempDistance=-1;
      isDim=true;
    }
    //设置自身的esn
    setStorage({
      key:'Myesn',
      data:dev_infomation.myesn
    })
    const hasBob = deviceList.some(item => item.esn === dev_infomation.esn);
    //距离小于一百米且不是同一个球球才显示
    if(!hasBob && TempDistance!==-1){        //去重
    setDeviceList([...deviceList, {
      // ballname:dev_infomation.dn,
      username:dev_infomation.un,
      esn:dev_infomation.esn,
      pid:dev_infomation.pid,
      dv:dev_infomation.dv,
      distance:TempDistance,
      isdim:isDim
    }]);
    getStorage({
      key:dev_infomation.esn,
      success(res){
        console.log('球球信息',res);
        if(res.data===null)
        {
          setStorage({
            key:dev_infomation.esn,
            data:{
              esn:dev_infomation.esn,
              pid:'1234',
              dv:'0.0.1',
              OtherSend:false,
              MySend:false,
              OtherSendInformation:false,
              InformationContent:'',
              MeetTimes:0,
              MeetMySend:false,
              MeetOtherSend:false,
              isMeet:false,
              FirstMeet:false,
              FirstMeetDay:'无',
              LastMeetDay:'无',
              Name:dev_infomation.dn,
              userName:dev_infomation.un,
              isSendInformation:false
            }
          })
        }
        else{
          getStorage({                  //每次打开开关搜索到熟悉的球球时偶遇逻辑
            key:dev_infomation.esn,
            success(res){
              setStorage({
                key:dev_infomation.esn,
                data:{
                  ...res.data,
                  MeetMySend:false,
                  isMeet:false,
                  Name:dev_infomation.dn,
                  userName:dev_infomation.un
                }
              })
            }
          })
        }
      },
    })
  }
    
  }, [sp_contact_info]);


  //附近球球发信息过来
  const sp_contact_msg = useProps(props => props[sp_contact_msg_code]);
  const [isFirstLoad2,setisFirstLoad2]=useState(false);
  
  useEffect(() => {
    //首次加载页面不执行
    if(!isFirstLoad2)
    {
      setisFirstLoad2(true);
      return;
    }
    console.log('触发了')
    const infomation=parseJSON(sp_contact_msg);
    if(sp_contact_msg!=='')
    {
      getStorage({
        key:infomation.ssn,
        success(res){
          if(res.data===null)    //如果发信息的球球未经过存储，设置初始值
          {
            setStorage({
              key:infomation.ssn,
              data:{
                esn:infomation.ssn,
                pid:'1234',
                dv:'0.0.1',
                OtherSend:true,
                MySend:false,
                OtherSendInformation:false,
                InformationContent:infomation.msg,
                MeetTimes:0,
                MeetMySend:false,
                MeetOtherSend:true,
                isMeet:false,
                FirstMeet:false,
                FirstMeetDay:'无',
                LastMeetDay:'无',
                Name:infomation.sdn,
                userName:infomation.sun,
                isSendInformation:true
              }
            })
          }
          else{
            setStorage({
              key:infomation.ssn,
              data:{
                ...res.data,
                OtherSend:true,
                MeetOtherSend:true,
                isSendInformation:true,
                InformationContent:infomation.msg
              },
            })
          }
        }
      })
    }
  }, [sp_contact_msg]);

//球球颜色随机获取
const spaceBalls = [space_ball,space_ball2, space_ball3, space_ball4];
const [RandomBallColor] = useState(() => 
  Array.from({ length: 20 }, () => 
    spaceBalls[Math.floor(Math.random() * spaceBalls.length)]
  )
);

//空间智能开关打开
  const start_match =()=>{
    if(!isOn)         //从关闭到打开
    {
      actions[sp_switch_code].set(true);
    }
    else{             //从打开到关闭
      setDeviceList([]);
      actions[sp_switch_code].set(false);
    }
    setisOn(!isOn);
  }


//正在寻找...文本动态化
  const [dots, setDots] = useState('...');
  useEffect(() => {
    const interval = setInterval(() => {
      setDots(prev => {
        if (prev === '...') return '.';
        if (prev === '.') return '..';
        return '...';
      });
    }, 500);
    return () => clearInterval(interval);
  }, []);

//页面跳转到好友列表
  const navigatetofriend=()=>{
    navigateTo({
      url:'/pages/friend/index',
    })
  }

//其他球球信息弹窗显示与关闭
  const [InformationPopupExist,setInformationPopupExist]=useState(false);
  const closeInformationPopup=()=>{
    setInformationPopupExist(false);
  }

//右上角胶囊按钮隐藏
  usePageEvent('onShow',()=>{
    hideMenuButton({});
  })

  //页面卸载时
  usePageEvent('onUnload',()=>{
    actions[sp_switch_code].set(false);
  })

  return (
    <>
    <View className={styles.bg}>
    { isOn ?
      <Text className={styles.search}>正在寻找{dots}</Text> :
    <View className={styles.remindercontainer}>
      <Text className={styles.reminder1}>点击开关</Text>
      <Text className={styles.reminder2}>开始寻找附近100米内的超级球球</Text>
    </View>}


    <Image src={space_ball} className={styles.ball_img} />

    { isOn &&
      <View>
      <View className={styles.circle1} />
      <View className={styles.circle2} />
      <View className={styles.circle3} />
    </View>}

    <View className={styles.spacecontainer}>
      <Button className={styles.space_btn} onClick={start_match}>
        <Image src={isOn ? match : start} className={styles.space_img} />
      </Button>
      {isOn ?
        <Text className={styles.match_font}>停止寻找</Text>:
        <Text className={styles.match_font}>开启偶遇</Text>}
    </View>

    <Button className={styles.friend_btn}>
      <Image className={styles.friend_img} src={friend} onClick={navigatetofriend}></Image>
    </Button>

    { deviceList[0]?.esn !== undefined  && deviceList.length >= 1 && deviceList.map((item, index) => (
      isOn &&
      <FriendBall 
        top={item.distance<=20?ClosePosition[index].y:FarPosition[index].y} 
        left={item.distance<=20?ClosePosition[index].x:FarPosition[index].x} 
        isDim={item.isdim}
        remain={remaining} 
        friendball_img={RandomBallColor[index]}
        // FriendBallName={item.ballname}
        FriendBallName='球球'
        FriendUserName={item.username}
        esn={item.esn}
        distance={item.distance}
        >
        </FriendBall>
    ))}

    </View>

    { InformationPopupExist &&
      <InformationPopup onClose={closeInformationPopup}></InformationPopup>}

    </>
  );
}


